package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存或者更新
     * @param latitude 纬度
     * @param longitude 经度
     */
    public void save(Double latitude, Double longitude, String address, Long userId) {
        //1、查询当前用户的地理位置数据是否存在
        Criteria criteria = Criteria.where("userId").is(userId);
        UserLocation location = mongoTemplate.findOne(Query.query(criteria), UserLocation.class);
        if(location == null) {
            //2、如果不存在，保存
            UserLocation ul = new UserLocation();
            ul.setUserId(userId);
            ul.setAddress(address);
            ul.setCreated(System.currentTimeMillis());
            ul.setUpdated(System.currentTimeMillis());
            ul.setLastUpdated(System.currentTimeMillis());
            ul.setLocation(new GeoJsonPoint(longitude,latitude));
            mongoTemplate.save(ul);
        }else {
            //3、如果存在，更新  update table  set location=xxxx  where userId=1
            Query query = Query.query(criteria);
            Update update = new Update();
            update.set("location",new GeoJsonPoint(longitude,latitude));
            update.set("address",address);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }
    }

    /**
     * 搜附近
     * @param userId  当前用户id
     * @param distance  距离范围
     * @return 附近人的所有id
     */
    public List<Long> findNear(Long userId, Long distance) {
        //1、根据用户id，查询当前用户的位置
        Criteria criteria = Criteria.where("userId").is(userId);
        UserLocation ul = mongoTemplate.findOne(Query.query(criteria), UserLocation.class);
        //2、已当前用户位置设置圆点
        GeoJsonPoint point = ul.getLocation();
        //3、构造半径
        Distance dis = new Distance(distance/1000, Metrics.KILOMETERS); //单位：千米
        //4、绘制圆形
        Circle circle = new Circle(point,dis);
        //5、查询
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        List<UserLocation> list = mongoTemplate.find(Query.query(criteria1), UserLocation.class);
        return CollUtil.getFieldValues(list,"userId",Long.class);
    }
}
